<?php

require_once __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

try {
    echo "🔗 创建用户角色关联...\n";

    // 获取用户和角色
    $user = \DB::table('users')->first();
    $role = \DB::table('roles')->first();

    if (!$user) {
        echo "❌ 没有找到用户\n";
        exit(1);
    }

    if (!$role) {
        echo "❌ 没有找到角色\n";
        exit(1);
    }

    echo "找到用户: {$user->username} (ID: {$user->id})\n";
    echo "找到角色: {$role->name} (ID: {$role->id})\n";

    // 检查是否已有关联
    $existing = \DB::table('user_roles')
        ->where('user_id', $user->id)
        ->where('role_id', $role->id)
        ->first();

    if ($existing) {
        echo "✅ 用户角色关联已存在\n";
    } else {
        // 创建关联
        \DB::table('user_roles')->insert([
            'user_id' => $user->id,
            'role_id' => $role->id,
            'start_date' => now()->format('Y-m-d'),
            'status' => 'active',
            'reason' => '系统初始化',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        echo "✅ 用户角色关联创建成功\n";
    }

    // 验证关联
    $userRoleCount = \DB::table('user_roles')->count();
    echo "📊 当前用户角色关联总数: {$userRoleCount}\n";

    echo "🎉 用户角色关联设置完成！\n";

} catch (Exception $e) {
    echo "❌ 错误：" . $e->getMessage() . "\n";
    echo "📍 文件：" . $e->getFile() . " 行：" . $e->getLine() . "\n";
}
